package com.cskaoyan.service.wx.wxy;

import com.cskaoyan.controller.wx.wxy.OrderUtils;
import com.cskaoyan.mapper.*;
import com.cskaoyan.module.bean.BaseRespVo;
import com.cskaoyan.module.bean.vo.GoodsListVo;
import com.cskaoyan.module.bean.vo.HandleOptionBeanVo;
import com.cskaoyan.module.bean.vo.OrderChannelVo;
import com.cskaoyan.module.bean.vo.WxOrderListVo;
import com.cskaoyan.module.pojo.*;
import com.cskaoyan.module.vo.wx.wxy.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class WxOrderServiceImpl implements WxOrderService {

    @Autowired
    MarketOrderMapper orderMapper;
    @Autowired
    MarketOrderGoodsMapper orderGoodsMapper;
    @Autowired
    MarketGoodsProductMapper goodsProductMapper;
    @Autowired
    MarketCommentMapper commentMapper;
    @Autowired
    MarketAddressMapper addressMapper;
    @Autowired
    MarketCartMapper cartMapper;
    @Autowired
    MarketCouponMapper couponMapper;
    @Autowired
    MarketCouponUserMapper couponUserMapper;
    @Autowired
    MarketGrouponMapper grouponMapper;
    @Autowired
    MarketGrouponRulesMapper grouponRulesMapper;
    @Autowired
    MarketSystemMapper systemMapper;


    @Override
    public WxOrderListDataVo selectOrder(Integer showType, Integer page, Integer limit, Integer userId) {
        //
        MarketOrderExample orderExample = new MarketOrderExample();
        MarketOrderExample.Criteria orderCriteria = orderExample.createCriteria();
        orderCriteria.andDeletedEqualTo(false);
        List<Short> statusList = new ArrayList<>();

        if (userId != null && userId != 0) {
            orderCriteria.andUserIdEqualTo(userId);
        }

        if (showType == 1) {
            statusList.add((short) 101);
            orderCriteria.andOrderStatusIn(statusList);
        }
        if (showType == 2) {
            statusList.add((short) 201);
            orderCriteria.andOrderStatusIn(statusList);
        }
        if (showType == 3) {
            statusList.add((short) 301);
            orderCriteria.andOrderStatusIn(statusList);
        }
        if (showType == 4) {
            statusList.add((short) 401);
            statusList.add((short) 402);
            orderCriteria.andOrderStatusIn(statusList);
        }


        //响应结果集
        List<WxOrderListVo> list = new ArrayList<>();
        List<MarketOrder> marketOrders = orderMapper.selectByExample(orderExample);

        for (MarketOrder marketOrder : marketOrders) {

            //用来封装order的信息
            WxOrderListVo wxOrderListVo = new WxOrderListVo();
            //用来封装orderGoods
            List<GoodsListVo> goodsList = new ArrayList<>();
            //通过orderId查询OrderGoods信息
            MarketOrderGoodsExample orderGoodsExample = new MarketOrderGoodsExample();
            MarketOrderGoodsExample.Criteria orderGoodsCriteria1 = orderGoodsExample.createCriteria();
            orderGoodsCriteria1.andOrderIdEqualTo(marketOrder.getId());
            orderGoodsCriteria1.andDeletedEqualTo(false);
            List<MarketOrderGoods> marketOrderGoods = orderGoodsMapper.selectByExample(orderGoodsExample);
            //将获取的结果封装的响应结果集
            wxOrderListVo.setOrderStatusText(isOrderStatusText(marketOrder.getOrderStatus()));
            wxOrderListVo.setAftersaleStatus(marketOrder.getAftersaleStatus());

            BigDecimal grouponPrice = marketOrder.getGrouponPrice();
            if (grouponPrice != null && !"".equals(grouponPrice) && !grouponPrice.equals(0)) {
                wxOrderListVo.setIsGroupin(true);
            } else {
                wxOrderListVo.setIsGroupin(false);
            }
            wxOrderListVo.setOrderSn(marketOrder.getOrderSn());
            wxOrderListVo.setActualPrice(marketOrder.getActualPrice());
            wxOrderListVo.setId(marketOrder.getId());

            //对goods信息进行封装
            for (MarketOrderGoods marketOrderGood : marketOrderGoods) {
                if (marketOrderGood.getDeleted()) {
                    break;
                }

                GoodsListVo goodsListVo = new GoodsListVo();
                goodsListVo.setId(marketOrderGood.getId());
                goodsListVo.setPicUrl(marketOrderGood.getPicUrl());
                goodsListVo.setPrice(marketOrderGood.getPrice());
                goodsListVo.setNumber(marketOrderGood.getNumber());
                goodsListVo.setGoodsName(marketOrderGood.getGoodsName());

                String specifications = marketOrderGood.getSpecifications();
                if (specifications.contains(",")) {
                    String[] split = specifications.split(",");
                    List<String> specificationsList = new ArrayList<>(Arrays.asList(split));
                    goodsListVo.setSpecifications(specificationsList);
                }
                goodsListVo.setSpecifications(new ArrayList<String>(Collections.singleton(specifications)));
                goodsList.add(goodsListVo);
            }
            wxOrderListVo.setGoodsList(goodsList);
            wxOrderListVo.setHandleOption(getHandleOptionBeanVo(marketOrder));
            list.add(wxOrderListVo);
        }

        PageHelper.startPage(page, limit);
        PageInfo<WxOrderListVo> pageInfo = new PageInfo<>(list);
        //list.size() !一定= total   → total ≥ list.size()
        long total = pageInfo.getTotal();//拿到满足条件的总的数据量（不考虑分页）
        int pages = pageInfo.getPages();

        return WxOrderListDataVo.data(total, pages, limit, page, list);
    }

    @Override
    public BaseRespVo selectOrderDetail(Integer orderId) {

        MarketOrder marketOrder = orderMapper.selectByPrimaryKey(orderId);
        Short orderStatus = marketOrder.getOrderStatus();
        if (orderStatus == 101 || orderStatus == 201) {
            return BaseRespVo.ok(noShipped(marketOrder));
        } else if (orderStatus == 301 || orderStatus == 401 || orderStatus == 402) {
            return BaseRespVo.ok(isShipped(marketOrder));
        } else {
           return BaseRespVo.ok(noShipped(marketOrder));
        }
    }

    @Override
    public int updateOrderDelete(Integer orderId) {
        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setId(orderId);
        marketOrder.setDeleted(true);
        marketOrder.setOrderStatus((short) 102);
        Date date = null;
        try {
            date = new SimpleDateFormat().parse("yyyy-MM-dd HH:mm:ss");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        marketOrder.setUpdateTime(date);

        return orderMapper.updateByPrimaryKeySelective(marketOrder);
    }

    @Override
    public int updateOrderCancel(Integer orderId) {
        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setId(orderId);
        marketOrder.setOrderStatus((short) 102);
        Date date = null;
        try {
            date = new SimpleDateFormat().parse("yyyy-MM-dd HH:mm:ss");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        marketOrder.setUpdateTime(date);

        return orderMapper.updateByPrimaryKeySelective(marketOrder);
    }

    @Override
    public int updateOrderRefund(Integer orderId) {
        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setId(orderId);
        marketOrder.setOrderStatus((short) 202);
        Date date = null;
        try {
            date = new SimpleDateFormat().parse("yyyy-MM-dd HH:mm:ss");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        marketOrder.setUpdateTime(date);
        return orderMapper.updateByPrimaryKeySelective(marketOrder);
    }

    @Override

    public MarketOrderGoods selectOrderGoods(Integer orderId, Integer goodsId) {
        return orderGoodsMapper.selectByPrimaryKey(orderId);
    }

    @Override
    public int updateComment(Integer orderGoodsId, String content, Short star, boolean hasPicture, String[] picUrls) {
        MarketComment marketComment = new MarketComment();
        marketComment.setValueId(orderGoodsId);
        marketComment.setType((byte) 0);
        marketComment.setContent(content);
        Subject subject = SecurityUtils.getSubject();
        MarketUser user = (MarketUser)subject.getPrincipals().getPrimaryPrincipal();
        marketComment.setAdminContent(null);
        marketComment.setUserId(user.getId());
        marketComment.setHasPicture(hasPicture);
        marketComment.setPicUrls(picUrls);
        marketComment.setStar(star);

        Date date = null;
        try {
            date = new SimpleDateFormat().parse("yyyy-MM-dd HH:mm:ss");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        marketComment.setAddTime(date);
        marketComment.setUpdateTime(date);
        marketComment.setDeleted(false);
        return commentMapper.insert(marketComment);
    }

    public BaseRespVo confirmOrder(Integer orderId) {
        MarketOrder marketOrder = orderMapper.selectByPrimaryKey(orderId);
        if (marketOrder !=null && !" ".equals(marketOrder)){
            marketOrder.setOrderStatus((short) 401);
            orderMapper.insertSelective(marketOrder);
            return BaseRespVo.ok("成功");
        }
        return null;
    }


    public HandleOptionBeanVo getHandleOptionBeanVo(MarketOrder marketOrder) {

        HandleOptionBeanVo handleOptionBeanVo = new HandleOptionBeanVo();

        //获取状态信息
        int status = marketOrder.getOrderStatus().intValue();

        if (status == 101) {
            handleOptionBeanVo.setCancel(true);
            handleOptionBeanVo.setPay(true);
        }

        //cancel
        if (status == 102 || status == 103) {
            handleOptionBeanVo.setDelete(true);
        }

        //pay
        if (status == 201) {
            handleOptionBeanVo.setRefund(true);
        }

        if (status == 202) {
            handleOptionBeanVo.setDelete(true);
        }


        if (status == 301) {
            handleOptionBeanVo.setConfirm(true);
        }

        //confirm
        if (status == 401 || status == 402) {
            handleOptionBeanVo.setDelete(true);
            handleOptionBeanVo.setRebuy(true);
            handleOptionBeanVo.setComment(true);
            handleOptionBeanVo.setAftersale(true);
        }

        return handleOptionBeanVo;
    }

    public String isOrderStatusText(Short orderStatus) {
        int value = orderStatus.intValue();

        if (value == 101) {
            return "未付款";
        } else if (value == 102) {
            return "用户取消";
        } else if (value == 103) {
            return "系统取消";
        } else if (value == 201) {
            return "已付款";
        } else if (value == 202) {
            return "申请退款";
        } else if (value == 203) {
            return "已退款";
        } else if (value == 301) {
            return "已发货";
        } else if (value == 401) {
            return "已收货";
        } else if (value == 402) {
            return "已收货";
        } else {
            return "";
        }
    }


    /**
     *
     * @param marketOrder
     * @return
     */
    public ShippedOrderDataVo isShipped(MarketOrder marketOrder) {

        //        List<GoodsListVo> goodsList = new ArrayList<>();
        ShippedOrderInfoVo shippedOrderInfoVo = new ShippedOrderInfoVo();
        List<OrderDetailGoodsVo> goodsList = new ArrayList<>();
        //将获取的结果封装的响应结果集
        shippedOrderInfoVo.setConsignee(marketOrder.getConsignee());
        shippedOrderInfoVo.setAddress(marketOrder.getAddress());
        shippedOrderInfoVo.setAddTime(marketOrder.getAddTime());
        shippedOrderInfoVo.setOrderSn(marketOrder.getOrderSn());
        shippedOrderInfoVo.setActualPrice(marketOrder.getActualPrice());
        shippedOrderInfoVo.setMobile(marketOrder.getMobile());
        shippedOrderInfoVo.setMessage(marketOrder.getMessage());
        shippedOrderInfoVo.setOrderStatusText(isOrderStatusText(marketOrder.getOrderStatus()));
        shippedOrderInfoVo.setAftersaleStatus(marketOrder.getAftersaleStatus());
        shippedOrderInfoVo.setGoodsPrice(marketOrder.getGoodsPrice());
        shippedOrderInfoVo.setCouponPrice(marketOrder.getCouponPrice());
        shippedOrderInfoVo.setId(marketOrder.getId());
        shippedOrderInfoVo.setFreightPrice(marketOrder.getFreightPrice());
        shippedOrderInfoVo.setHandleOption(getHandleOptionBeanVo(marketOrder));

        List<OrderChannelVo> orderChannelVos = orderMapper.selectChannel();
        for (OrderChannelVo orderChannelVo : orderChannelVos) {
            if (orderChannelVo.getCode().equals(marketOrder.getShipChannel())){
                shippedOrderInfoVo.setExpCode(marketOrder.getShipChannel());
                shippedOrderInfoVo.setExpName(orderChannelVo.getName());
            }
        }
        shippedOrderInfoVo.setExpNo(marketOrder.getShipSn());

        MarketOrderGoodsExample orderGoodsExample = new MarketOrderGoodsExample();
        MarketOrderGoodsExample.Criteria orderGoodsCriteria1 = orderGoodsExample.createCriteria();
        orderGoodsCriteria1.andOrderIdEqualTo(marketOrder.getId());
        List<MarketOrderGoods> marketOrderGoods = orderGoodsMapper.selectByExample(orderGoodsExample);
        //对goods信息进行封装
        for (MarketOrderGoods marketOrderGood : marketOrderGoods) {

            OrderDetailGoodsVo orderDetailGoodsVo = new OrderDetailGoodsVo();
            orderDetailGoodsVo.setId(marketOrderGood.getId());
            orderDetailGoodsVo.setOrderId(marketOrderGood.getOrderId());
            orderDetailGoodsVo.setGoodsId(marketOrderGood.getGoodsId());
            orderDetailGoodsVo.setGoodsName(marketOrderGood.getGoodsName());
            orderDetailGoodsVo.setGoodsSn(marketOrderGood.getGoodsSn());
            orderDetailGoodsVo.setProductId(marketOrderGood.getProductId());
            orderDetailGoodsVo.setNumber(marketOrderGood.getNumber());
            orderDetailGoodsVo.setPrice(marketOrderGood.getPrice());
            orderDetailGoodsVo.setPicUrl(marketOrderGood.getPicUrl());
            orderDetailGoodsVo.setComment(marketOrderGood.getComment());
            orderDetailGoodsVo.setAddTime(marketOrderGood.getAddTime());
            orderDetailGoodsVo.setUpdateTime(marketOrderGood.getUpdateTime());

            String specifications = marketOrderGood.getSpecifications();
            if (specifications.contains(",")) {
                String[] split = specifications.split(",");
                List<String> specificationsList = new ArrayList<>(Arrays.asList(split));
                orderDetailGoodsVo.setSpecifications(specificationsList);
            }
            orderDetailGoodsVo.setSpecifications(Collections.singletonList(specifications));
            goodsList.add(orderDetailGoodsVo);
        }

        ShippedOrderDataVo shippedOrderDataVo = new ShippedOrderDataVo();
        shippedOrderDataVo.setOrderInfo(shippedOrderInfoVo);
        shippedOrderDataVo.setOrderGoods(goodsList);
        shippedOrderDataVo.setExpressInfo(null);

        return shippedOrderDataVo;

    }

    /**
     * @param marketOrder
     * @return
     */
    public OrderDetailDataVo noShipped(MarketOrder marketOrder) {

        //        List<GoodsListVo> goodsList = new ArrayList<>();
        OrderInfoVo orderInfoVo = new OrderInfoVo();
        List<OrderDetailGoodsVo> goodsList = new ArrayList<>();
        //将获取的结果封装的响应结果集
        orderInfoVo.setConsignee(marketOrder.getConsignee());
        orderInfoVo.setAddress(marketOrder.getAddress());
        orderInfoVo.setAddTime(marketOrder.getAddTime());
        orderInfoVo.setOrderSn(marketOrder.getOrderSn());
        orderInfoVo.setActualPrice(marketOrder.getActualPrice());
        orderInfoVo.setMobile(marketOrder.getMobile());
        orderInfoVo.setMessage(marketOrder.getMessage());
        orderInfoVo.setOrderStatusText(isOrderStatusText(marketOrder.getOrderStatus()));
        orderInfoVo.setAftersaleStatus(marketOrder.getAftersaleStatus());
        orderInfoVo.setGoodsPrice(marketOrder.getGoodsPrice());
        orderInfoVo.setCouponPrice(marketOrder.getCouponPrice());
        orderInfoVo.setId(marketOrder.getId());
        orderInfoVo.setFreightPrice(marketOrder.getFreightPrice());

        orderInfoVo.setHandleOption(getHandleOptionBeanVo(marketOrder));


        MarketOrderGoodsExample orderGoodsExample = new MarketOrderGoodsExample();
        MarketOrderGoodsExample.Criteria orderGoodsCriteria1 = orderGoodsExample.createCriteria();
        orderGoodsCriteria1.andOrderIdEqualTo(marketOrder.getId());
        List<MarketOrderGoods> marketOrderGoods = orderGoodsMapper.selectByExample(orderGoodsExample);
        //对goods信息进行封装
        for (MarketOrderGoods marketOrderGood : marketOrderGoods) {

            OrderDetailGoodsVo orderDetailGoodsVo = new OrderDetailGoodsVo();
            orderDetailGoodsVo.setId(marketOrderGood.getId());
            orderDetailGoodsVo.setOrderId(marketOrderGood.getOrderId());
            orderDetailGoodsVo.setGoodsId(marketOrderGood.getGoodsId());
            orderDetailGoodsVo.setGoodsName(marketOrderGood.getGoodsName());
            orderDetailGoodsVo.setGoodsSn(marketOrderGood.getGoodsSn());
            orderDetailGoodsVo.setProductId(marketOrderGood.getProductId());
            orderDetailGoodsVo.setNumber(marketOrderGood.getNumber());
            orderDetailGoodsVo.setPrice(marketOrderGood.getPrice());
            orderDetailGoodsVo.setPicUrl(marketOrderGood.getPicUrl());
            orderDetailGoodsVo.setComment(marketOrderGood.getComment());
            orderDetailGoodsVo.setAddTime(marketOrderGood.getAddTime());
            orderDetailGoodsVo.setUpdateTime(marketOrderGood.getUpdateTime());

            String specifications = marketOrderGood.getSpecifications();
            if (specifications.contains(",")) {
                String[] split = specifications.split(",");
                List<String> specificationsList = new ArrayList<>(Arrays.asList(split));
                orderDetailGoodsVo.setSpecifications(specificationsList);
            }
            orderDetailGoodsVo.setSpecifications(Collections.singletonList(specifications));
            goodsList.add(orderDetailGoodsVo);
        }
        OrderDetailDataVo orderDetailDataVo = new OrderDetailDataVo();
        orderDetailDataVo.setOrderInfo(orderInfoVo);
        orderDetailDataVo.setOrderGoods(goodsList);
        orderDetailDataVo.setExpressInfo(null);
        return orderDetailDataVo;
    }


    @Override
    public BaseRespVo insertOrder(Integer addressId, Integer cartId, Integer couponId, Integer grouponLinkId, Integer grouponRulesId, String message, Integer userCouponId) {
        Subject subject = SecurityUtils.getSubject();
        MarketUser user = (MarketUser)subject.getPrincipals().getPrimaryPrincipal();

        MarketOrder marketOrder = new MarketOrder();

        marketOrder.setId(null);
        marketOrder.setUserId(user.getId());
        marketOrder.setOrderSn(OrderUtils.getOrderCode(user.getId()));
        marketOrder.setOrderStatus((short) 101);
        marketOrder.setAftersaleStatus((short) 0);
        //获取收货信息
        MarketAddress address = addressMapper.selectByPrimaryKey(addressId);
        marketOrder.setConsignee(address.getName());
        marketOrder.setMobile(address.getTel());
        marketOrder.setAddress(address.getProvince() +
                address.getCity() + address.getCounty() + address.getAddressDetail());
        marketOrder.setMessage(message);
        //通过cart获得订单信息
        MarketCart cart = cartMapper.selectByPrimaryKey(cartId);


        marketOrder.setGoodsPrice(cart.getPrice());

        //获取coupon信息
        if (couponId != 0){
            MarketCoupon coupon = couponMapper.selectByPrimaryKey(couponId);
            marketOrder.setCouponPrice(coupon.getDiscount());
        }else {
            marketOrder.setCouponPrice(BigDecimal.valueOf(0));
        }

//        MarketCouponUser couponUser = couponUserMapper.selectByPrimaryKey(userCouponId);
//        if (userCouponId != 0){
//            marketOrder.setIntegralPrice();
//        }


        if (grouponRulesId != 0){
            MarketGrouponRules grouponRules = grouponRulesMapper.selectByPrimaryKey(grouponRulesId);
            marketOrder.setGrouponPrice(grouponRules.getDiscount());
        }else {
            marketOrder.setGrouponPrice(BigDecimal.valueOf(0));
        }


        MarketSystem marketSystem1= systemMapper.selectByPrimaryKey(6);
        MarketSystem marketSystem2 = systemMapper.selectByPrimaryKey(8);

        if (marketOrder.getGoodsPrice().intValue() > Integer.parseInt(marketSystem1.getKeyValue())){
            marketOrder.setFreightPrice(BigDecimal.valueOf(0));
        }else {
            marketOrder.setFreightPrice(BigDecimal.valueOf(Integer.parseInt(marketSystem2.getKeyValue())));
        }
        marketOrder.setIntegralPrice(BigDecimal.valueOf(0));
        marketOrder.setOrderPrice(BigDecimal.valueOf((marketOrder.getGoodsPrice().intValueExact() + marketOrder.getFreightPrice().intValue() - marketOrder.getCouponPrice().intValueExact())));
        marketOrder.setActualPrice(BigDecimal.valueOf((marketOrder.getOrderPrice().intValueExact())));

        Date date1 = null;
        try {
            date1 = new SimpleDateFormat().parse("yyyy-MM-dd HH:mm:ss");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        marketOrder.setEndTime(date1);
        orderMapper.insert(marketOrder);


        MarketOrderGoods orderGoods = new MarketOrderGoods();

        orderGoods.setOrderId(marketOrder.getId());
        orderGoods.setGoodsId(cart.getGoodsId());
        orderGoods.setGoodsName(cart.getGoodsName());
        orderGoods.setGoodsSn(cart.getGoodsSn());
        orderGoods.setProductId(cart.getProductId());
        orderGoods.setNumber(cart.getNumber().shortValue());
        orderGoods.setPrice(cart.getPrice());
        orderGoods.setSpecifications(cart.getSpecifications());
        orderGoods.setPicUrl(cart.getPicUrl());
        orderGoods.setComment(0);

        Date date2 = null;
        try {
            date2 = new SimpleDateFormat().parse("yyyy-MM-dd HH:mm:ss");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        orderGoods.setAddTime(date2);
        orderGoodsMapper.insertSelective(orderGoods);
        WxOrderSubmitDataVo wxOrderSubmitDataVo = new WxOrderSubmitDataVo();
        wxOrderSubmitDataVo.setOrderId(marketOrder.getId());
        wxOrderSubmitDataVo.setGrouponLinkId(grouponLinkId);

        return BaseRespVo.ok(wxOrderSubmitDataVo);
    }
}
